<?php

namespace common\models;

use Yii;
use yii\behaviors\TimestampBehavior;

/**
 * This is the model class for table "{{%article}}".
 *
 * @property integer $id
 * @property integer $cid
 * @property string $title
 * @property string $thumb
 * @property string $content
 * @property integer $created_at
 * @property integer $updated_at
 */
class Article extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%article}}';
    }

    // 行为
    public function behaviors()
    {
        return [
          [ 'class' => TimestampBehavior::className()]
        ];
    }

    /**
     * 排序倒序
     */
    public static function find()
    {
        return parent::find()->orderBy('sort desc, id desc');
    }

    // 获取栏目
    public function getCategory()
    {
        return $this->hasOne(Category::className(), ['id' => 'cid']);
    }

    /**
     * 获取当前栏目下的所有文章
     * @param $cid 栏目ID
     * @return array
     */
    public static function getArticles($cid)
    {
        return static::find()->select(['title', 'cid', 'id', 'thumb'])->where(['cid' => $cid])->all();
    }


    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['cid', 'title'], 'required'],
            [['cid', 'sort', 'status'], 'integer'],
            ['sort', 'default', 'value' => 0],
            [['content', 'thumb'], 'string'],
            [['title'], 'string', 'max' => 255],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'cid' => '栏目',
            'title' => '文章标题',
            'thumb' => '缩略图',
            'content' => '内容',
            'sort' => '排序',
            'status' => '文章状态',
            'created_at' => '添加时间',
            'updated_at' => '更新时间',
        ];
    }
}
